package Demo;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIP = null;
    private int serverPort;
    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("客户端启动!");
        while (true) {
            System.out.println(("请输入要发送的消息:"));
            String request = scanner.nextLine();
            DatagramPacket reqPacket = new DatagramPacket(request.getBytes(), request.getBytes().length
                    , InetAddress.getByName(serverIP), serverPort);
            socket.send(reqPacket);
            DatagramPacket resPacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(resPacket);
            String response = new String(resPacket.getData(), 0, resPacket.getLength());
            System.out.println(response);
        }

    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 8080);
        client.start();

    }
}
